//
//  YWNoQrcodePostTroubleTableViewController.m
//  maintain
//
//  Created by 烟雨云渊 on 16/8/29.
//  Copyright © 2016年 ewin. All rights reserved.
//

#import "YWNoQrcodePostTroubleTableViewController.h"
#import "UIColor+CustomColors.h"
#import "YWMacro.h"
#import "YWConst.h"
#import "YWCommonTool.h"
#import "YWLoginTool.h"
#import "MBProgressHUD.h"

#import "YWWriteNoteCell.h"
#import "YWTakePhotoCell.h"
//#import "YWImageView.h"
#import "YWPhotoView.h"

#import "YWBuilding.h"
#import "YWBuildingManager.h"
#import "YWApartment.h"
#import "YWFloor.h"
#import "YWLocation.h"
#import "YWDBTool.h"
#import "YWPicture.h"

#import "YWSelectBuildingTableViewController.h"
#import "YWSelectApartmentTableViewController.h"
#import "YWSelectFloorTableViewController.h"
#import "YWSelectLocationTableViewController.h"
#import "YWSingleSelectEquSystemTypeTableViewController.h"

#import "YWHandler.h"
#import "YWMission.h"
#import "YWCirculationInfo.h"
#import "YWMissionManager.h"
#import "YWCirculationManager.h"
#import "YWNotifyManager.h"
#import "YWResourceManager.h"
#import "YWEquipment.h"
#import "YWReportTroubleModel.h"
#import "YWReportTroubleManager.h"
#import "YWTroubleMissionModel.h"
#import "YWEquipmentType.h"
#import "YWEquipmentManager.h"

@interface YWNoQrcodePostTroubleTableViewController ()<YWSelectBuildingTableViewControllerDelegate,YWSelectApartmentTableViewControllerDelegate,YWSelectFloorTableViewControllerDelegate,YWSelectLocationTableViewControllerDelegate,YWWriteNoteCellDelegate,YWTakePhotoCellDelegate,YWSingleSelectEquSystemTypeTableViewControllerDelegate>{
    YWBuilding *currentBuilding;
    YWApartment *currentApartment;
    YWFloor *currentFloor;
    YWLocation *currentLocation;
    NSString *troubleNote;
}
@property (nonatomic, strong) NSArray *allBuildings;
@property (nonatomic, strong) NSArray *totalImageNameArray;
@property (nonatomic, strong) UIView *footView;
@property (nonatomic, strong) YWEquipmentSystemType * equipmentSystemType;
@property (nonatomic, weak) MBProgressHUD* HUD;
@end

@implementation YWNoQrcodePostTroubleTableViewController

- (instancetype)init{
    return [super initWithStyle:UITableViewStyleGrouped];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSLocalizedString(@"recordReportTrouble", nil);//@"录入报障";
    self.view.backgroundColor = [UIColor customBackgroudColor];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(backToBeforeView:)];
    [self initTableView];
}

- (void)initTableView{
    currentBuilding = self.allBuildings.count>0?self.allBuildings[0]:nil;
    
    [self.tableView registerClass:[YWWriteNoteCell class] forCellReuseIdentifier:YWWriteNoteCellIdentifier];
    [self.tableView registerClass:[YWTakePhotoCell class] forCellReuseIdentifier:YWTakePhotoCellIdentifier];
    self.tableView.backgroundColor = [UIColor customBackgroudColor];
    self.tableView.separatorColor = [UIColor customLineColor];
    self.tableView.sectionFooterHeight = 1.0;
    self.tableView.tableFooterView = self.footView;
}

- (NSArray *)allBuildings{
    if (!_allBuildings) {
        _allBuildings = [[YWBuildingManager shareManager] allBuilding];
    }
    return _allBuildings;
}
#pragma mark - Table view data source
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section <=4) {
        return 44;
    }else if (indexPath.section == 5){
        return 90;
    }else if (indexPath.section == 6){
        CGFloat imageH = YWPhotoSize*(self.totalImageNameArray.count/4+1) + YWPhotoGap*(self.totalImageNameArray.count/4);
        return 10*2 + imageH;
    }else{
        return 0;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 7;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section <= 4) {
        static NSString *reuseIdentifier = @"noQrcodePostTroubleCellReuseIdentifier";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
            cell.textLabel.font = kContentFont;
            cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        }
        [self configureCell:cell withIndexPath:indexPath];
        return cell;
    }else if (indexPath.section == 5){
        YWWriteNoteCell *cell = [tableView dequeueReusableCellWithIdentifier:YWWriteNoteCellIdentifier];
        cell.delegate = self;
        cell.textViewPlaceHolder = NSLocalizedString(@"pleaseEnterDetailReportTroubleMessage", nil);//@"请输入详细故障信息";
        return cell;
    }else if (indexPath.section == 6){
        YWTakePhotoCell *cell = [tableView dequeueReusableCellWithIdentifier:YWTakePhotoCellIdentifier];
        cell.delegate = self;
        cell.totalImageNameArray = self.totalImageNameArray;
        return cell;
    }else{
        return [[UITableViewCell alloc] init];
    }
}

- (void)configureCell:(UITableViewCell*)cell withIndexPath:(NSIndexPath*)indexPath{
    if (indexPath.section == 0) {
        NSString *buildingShowName = [YWLoginTool buildingShowName];
        buildingShowName = buildingShowName.length ? buildingShowName:@"楼盘";
        cell.textLabel.text = currentBuilding.buildingName.length ? currentBuilding.buildingName : [NSString stringWithFormat:@"选择%@",buildingShowName];
    }else if (indexPath.section ==1){
        NSString *apartmentShowName = [YWLoginTool apartmentShowName];
        apartmentShowName = apartmentShowName.length ? apartmentShowName:@"楼栋";
        cell.textLabel.text = currentApartment.apartmentName.length ? currentApartment.apartmentName : [NSString stringWithFormat:@"选择%@",apartmentShowName];
    }else if (indexPath.section ==2){
        NSString *floorShowName = [YWLoginTool floorShowName];
        floorShowName = floorShowName.length ? floorShowName:@"楼层";
        cell.textLabel.text = currentFloor.floorName.length ? currentFloor.floorName : [NSString stringWithFormat:@"选择%@",floorShowName];
    }else if (indexPath.section  ==3){
        NSString *locationShowName = [YWLoginTool locationShowName];
        locationShowName = locationShowName.length ? locationShowName:@"方位";
        cell.textLabel.text = currentLocation.locationName.length ? currentLocation.locationName : [NSString stringWithFormat:@"选择%@",locationShowName];
    }else if (indexPath.section == 4){
        cell.textLabel.text = self.equipmentSystemType.systemTypeName;
    }
}

- (UIView*)tableView:(UITableView*)tableView viewForHeaderInSection:(NSInteger)section
{
    static NSString* HeaderIdentifier = @"YWNoQrcodePostTroubleTableViewControllerForHeaderInSection";
    UITableViewHeaderFooterView* headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderIdentifier];
    if (headerView == nil) {
        headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:HeaderIdentifier];
        UILabel* label = [[UILabel alloc] init];
        label.textAlignment = NSTextAlignmentLeft;
        label.textColor = [UIColor customTextGrayColor];
        label.tag = 2006;
        label.numberOfLines = 0;
        label.font = KSmallContentFont;
        [headerView addSubview:label];
    }
    NSString *headText = [self titleForHeaderInSection:section];
    UILabel* label = [headerView viewWithTag:2006];
    label.text = headText;
    label.frame = CGRectMake(15, 0, SCREEN_WIDTH - 2 * 15, 35);
    return headerView;
}

-(NSString *)titleForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        NSString *buildingShowName = [YWLoginTool buildingShowName];
        return buildingShowName.length?[NSString stringWithFormat:@"选择%@",buildingShowName]:@"选择楼盘";
    }else if (section == 1) {
        NSString *apartmentShowName = [YWLoginTool apartmentShowName];
        return apartmentShowName.length?[NSString stringWithFormat:@"选择%@",apartmentShowName]:@"选择楼栋";
    }else if (section == 2){
        NSString *floorShowName = [YWLoginTool floorShowName];
        return floorShowName.length?[NSString stringWithFormat:@"选择%@",floorShowName]:@"选择楼层";
    }else if (section == 3){
        NSString *locationShowName = [YWLoginTool locationShowName];
        return locationShowName.length?[NSString stringWithFormat:@"选择%@",locationShowName]:@"选择位置";
    }else if (section == 4){
        return @"报障类别";
    }else if (section == 5){
        return @"故障描述";
    }else if (section == 6){
        return @"拍照上传";
    }
    return nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 35;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        YWSelectBuildingTableViewController *selectBuildingVC = [[YWSelectBuildingTableViewController alloc] init];
        selectBuildingVC.delegate = self;
        selectBuildingVC.ownBuilding = currentBuilding;
        [self.navigationController pushViewController:selectBuildingVC animated:YES];
    }else if (indexPath.section == 1){
        if (currentBuilding.buildingName.length) {
            YWSelectApartmentTableViewController *selectApartmentVC = [[YWSelectApartmentTableViewController alloc] init];
            selectApartmentVC.delegate = self;
            selectApartmentVC.canEdit = YES;
            selectApartmentVC.building = currentBuilding;
            selectApartmentVC.ownApartment = currentApartment;
            [self.navigationController pushViewController:selectApartmentVC animated:YES];
        }else{
            NSString *buildingShowName = [YWLoginTool buildingShowName];
            [YWCommonTool showTextHUDWithContent:[NSString stringWithFormat:@"请先选择%@",buildingShowName?:@"楼盘"]];
        }
    }else if (indexPath.section == 2){
        if (currentApartment.apartmentName.length) {
            YWSelectFloorTableViewController *selectFloorVC = [[YWSelectFloorTableViewController alloc] init];
            selectFloorVC.delegate = self;
            selectFloorVC.canEdit = YES;
            selectFloorVC.apartment = currentApartment;
            selectFloorVC.ownFloor = currentFloor;
            [self.navigationController pushViewController:selectFloorVC animated:YES];
        }else{
            NSString *apartmentShowName = [YWLoginTool apartmentShowName];
            [YWCommonTool showTextHUDWithContent:[NSString stringWithFormat:@"请先选择%@",apartmentShowName?:@"楼栋"]];
        }
    }else if (indexPath.section == 3){
        if (currentFloor.floorName.length) {
            YWSelectLocationTableViewController *selectLocationVC = [[YWSelectLocationTableViewController alloc] init];
            selectLocationVC.delegate = self;
            selectLocationVC.canEdit = YES;
            selectLocationVC.floor = currentFloor;
            selectLocationVC.ownLocation = currentLocation;
            [self.navigationController pushViewController:selectLocationVC animated:YES];
        }else{
            NSString *floorShowName = [YWLoginTool floorShowName];
            [YWCommonTool showTextHUDWithContent:[NSString stringWithFormat:@"请先选择%@",floorShowName?:@"楼层"]];
        }
    }else if (indexPath.section == 4){
    YWSingleSelectEquSystemTypeTableViewController * selectSystemTypeVC = [[YWSingleSelectEquSystemTypeTableViewController alloc] init];
        selectSystemTypeVC.currentEquipmentSystemType = self.equipmentSystemType;
        selectSystemTypeVC.delegate = self;
        [self.navigationController pushViewController:selectSystemTypeVC animated:YES];
    }
}
#pragma mark - YWSelectBuildingTableViewControllerDelegate
-(void)popSelectedBuilding:(YWBuilding *)building{
    if (building && ![currentBuilding.buildingId isEqualToString:building.buildingId]) {
        currentBuilding = building;
        currentApartment = nil;
        currentFloor = nil;
        currentLocation = nil;
        [self.tableView reloadData];
    }
}
#pragma mark - YWSelectApartmentTableViewControllerDelegate
- (void)popSelectedApartment:(YWApartment *)apartment{
    if (apartment.apartmentId == -1) {
        currentApartment = apartment;
        [self.tableView reloadData];
    }else if (apartment && currentApartment.apartmentId != apartment.apartmentId) {
        currentApartment = apartment;
        currentFloor = nil;
        currentLocation = nil;
        [self.tableView reloadData];
    }
}
#pragma mark - YWSelectFloorTableViewControllerDelegate
- (void)popSelectedFloor:(YWFloor *)floor{
    if (floor.floorId == -1) {
        currentFloor = floor;
        [self.tableView reloadData];
    }else if (floor && currentFloor.floorId != floor.floorId){
        currentFloor = floor;
        currentLocation = nil;
        [self.tableView reloadData];
    }
}
#pragma mark - YWSelectLocationTableViewControllerDelegate
- (void)popSelectedLocation:(YWLocation *)location{
    if (location.locationId == -1) {
        currentLocation = location;
        [self.tableView reloadData];
    }else if (location && currentLocation.locationId != location.locationId) {
        currentLocation = location;
        [self.tableView reloadData];
    }
}
#pragma mark - YWTakePhotoCellDelegate
- (void)resetCellFrameWithImages:(NSArray *)images cell:(UITableViewCell *)cell{
    NSArray* arr = [[NSArray alloc] initWithArray:images copyItems:YES];
    self.totalImageNameArray = arr;
    
    [self.tableView reloadData];
}

#pragma mark - YWWriteNoteCellDelegate
- (void)passNote:(NSString *)note{
    troubleNote = note;
}

- (UIView *)footView{
    if (!_footView) {
        UIView * footView = [[UIView alloc] init];
        footView.frame = CGRectMake(0, 0, SCREEN_WIDTH, kButtonH+30*2);
        footView.backgroundColor = [UIColor customBackgroudColor];
        _footView = footView;
        CGFloat buttonWidth = SCREEN_WIDTH-20*2;
        
        UIButton *button = [[UIButton alloc] init];
        button.clipsToBounds = YES;
        button.layer.cornerRadius = 4.0;
        button.frame = CGRectMake(20, 30, buttonWidth, kButtonH);
        [button setTitle:@"提交" forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        button.backgroundColor = [UIColor customBlueColor];
        [button addTarget:self action:@selector(clickSenderButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
        [_footView addSubview:button];
    }
    return _footView;
}

- (void)clickSenderButtonEvent:(id)sender{
    [self.view endEditing:YES];
    //提交录入的报障
    if (currentBuilding.buildingId.length==0 || currentApartment.apartmentName.length==0 || currentFloor.floorName.length==0 || currentLocation.locationName.length==0) {
        [YWCommonTool showTextHUDWithContent:@"报障位置信息不完整"];
        return;
    }
    if (troubleNote.length==0) {
        [YWCommonTool showTextHUDWithContent:@"请完善报障描述"];
        return;
    }
    if ([YWCommonTool isContainsEmoji:troubleNote]) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextCantContainEmoji, nil)];
        return;
    }
    if (troubleNote.length > 100) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextNoteMax, nil)];
        return;
    }
    
    //点击提交
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"确认提交" message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.HUD show:YES];
        [self commitTrouble];
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)commitTrouble{
    
    //保存 录入的报障的新建的位置
    if (currentApartment && currentApartment.apartmentId<0 && currentFloor && currentFloor.floorId<0 && currentLocation && currentLocation.locationId<0) {
        [[YWDBTool shareDBTool] updateIdAndNameWithBuilding:currentBuilding apartment:currentApartment floor:currentFloor location:currentLocation];
    }
//    if (currentApartment && currentApartment.apartmentId<0) {
//        currentApartment.buildingId = currentBuilding.buildingId;
//        [[YWDBTool shareDBTool] updateApartmentWithArray:@[currentApartment]];
//    }
//    if (currentFloor && currentFloor.floorId<0) {
//        currentFloor.apartmentId = currentApartment.apartmentId;
//        [[YWDBTool shareDBTool] updateFloorWithArray:@[currentFloor]];
//    }
//    if (currentLocation && currentLocation.locationId<0) {
//        currentLocation.floorId = currentFloor.floorId;
//        [[YWDBTool shareDBTool] updateLocationWithArray:@[currentLocation]];
//    }
    
    YWReportTroubleModel * reportTrouble = [self createPostReportTrouble];
    BOOL saveReportTrouble = [[YWReportTroubleManager shareManager] updateReportTroubleWithArray:@[reportTrouble]];
    
    NSArray* pictures = [self createPictures:reportTrouble];
    BOOL savePicturesToDB = [[YWResourceManager shareManager] savePicturesToDBWithArray:pictures];
    
    if (saveReportTrouble && savePicturesToDB) {
        [self.HUD hide:YES];
        //创建保存流转信息
        [[YWCirculationManager shareManager] createAndSaveLocalCirculationInfoWithType:YWCirculationInfoTypePostTrouble troubleId:reportTrouble.troubleId recipient:nil note:nil];
        //上传
        [[YWReportTroubleManager shareManager] startUploadReportTrouble:reportTrouble pictures:pictures];
//        YWTroubleMissionModel * troubleMission = [[YWTroubleMissionModel alloc] init];
//        troubleMission.trouble = reportTrouble;
//        [[YWMissionManager shareManager] startUploadRecords:nil troubleMissionModel:troubleMission pictures:pictures];
        
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextConfirmSubmitPostTroubleFinished, nil)];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self popToSomeViewController];
        });
    }
    else {
        [self.HUD hide:YES];
        YWLog(@"保存数据库失败");
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextSubmitPostTroubleFail, nil)];
    }
}


- (YWReportTroubleModel*)createPostReportTrouble{
    NSTimeInterval nowTime = [[NSDate date] timeIntervalSince1970] * 1000;
    YWReportTroubleModel * reportTrouble = [[YWReportTroubleModel alloc] init];
    reportTrouble.troubleId = -1 * [YWCommonTool randNumber];
    reportTrouble.maintenanceTypeId = YWMaintenanceTypeTrouble;
    reportTrouble.troubleStatus = YWTroubleMissionStatusUnAssign;
    reportTrouble.note = [troubleNote?:@"" stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    reportTrouble.reportTime = nowTime;
    if (![self.equipmentSystemType.systemTypeName isEqualToString:@"无"]) {
        reportTrouble.systemTypeId = self.equipmentSystemType.systemTypeId;
    }
    YWLoginUser* loginUser = [YWLoginTool loginUser];
    YWHandler *creator = [[YWHandler alloc]init];
    creator.uniqueId = loginUser.uniqueId;
    creator.userName = loginUser.userName;
    creator.mobile = loginUser.mobile;
    creator.headIcon = loginUser.headIcon;
    reportTrouble.reporter = creator;
    reportTrouble.channel = YWPostTroubleTypeEwinApp;
    reportTrouble.qrcodeId = nil;//_currentEquipment.qrcodeId;
    reportTrouble.location = currentLocation;
    YWBuilding* building = currentBuilding;
    if (building==nil) {
        building = [[YWBuildingManager shareManager] buildingWithLocationId:currentLocation.locationId];
    }
    reportTrouble.building = building;
    reportTrouble.uniqueTag = [YWCommonTool randStringId];
   return reportTrouble;
}

- (NSArray*)createPictures:(YWReportTroubleModel*)mission
{
    NSMutableArray* pictures = [NSMutableArray array];
    for (int i = 0; i < [self.totalImageNameArray count]; i++) {
        YWPicture* picture = [[YWPicture alloc] init];
        picture.pictureId = [YWCommonTool randStringId];
        picture.pictureName = self.totalImageNameArray[i];
        picture.isLocalImage = YES;
        picture.uploadStatus = YWPictureUploadStatusNull;
        picture.missionId = mission.troubleId;
        picture.maintenanceType = mission.maintenanceTypeId;
        picture.equipmentId = mission.equipment.equipmentId;
        [pictures addObject:picture];
    }
    return pictures;
}

-(void)popToSomeViewController{
    [self.navigationController popViewControllerAnimated:YES];
}

- (MBProgressHUD*)HUD
{
    if (!_HUD) {
        MBProgressHUD* hud = [[MBProgressHUD alloc] initWithView:[UIApplication sharedApplication].keyWindow];
        hud.labelFont = kHUDLabelFont;
        hud.labelText = NSLocalizedString(kTextSubmitTask, nil);
        hud.dimBackground = YES;
        //hud.animationType = MBProgressHUDAnimationZoom;
        _HUD = hud;
        _HUD.tag = kMBProgressHUDTag;
        [self.navigationController.view addSubview:hud];
    }
    return _HUD;
}

- (YWEquipmentSystemType*)equipmentSystemType{
    if (!_equipmentSystemType) {
        _equipmentSystemType = [[[YWEquipmentManager shareManager] allEquipmentSystemType] firstObject];
    }
    return _equipmentSystemType;
}

#pragma mark-YWSingleSelectEquSystemTypeTableViewControllerDelegate
- (void)popSelectedEquipmentSystemType:(YWEquipmentSystemType*)equipmentSystemType{
    self.equipmentSystemType = equipmentSystemType;
    [self.tableView reloadData];
}

- (void)backToBeforeView:(id)sender{
    [self.view endEditing:YES];
    UIAlertController* alertController= [UIAlertController alertControllerWithTitle:@"退出报障" message:@"您确定退出此次报障吗？" preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:alertController animated:YES completion:nil];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self.navigationController popViewControllerAnimated:YES];
    }]];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
